package org.zz.database;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Set;

public class MemberAccess {
	private HashMap<String, Object> fieldnameToValue;
	private static HashMap<String,Boolean> fieldForSearch = new HashMap<String,Boolean>();
	private static HashMap<String, Float> fieldBoosts = new HashMap<String, Float>();

	public MemberAccess() {
		fieldnameToValue = new HashMap<String, Object>();
	}

	public void init(Object obj) {
		fieldnameToValue.clear();
		Field[] fields = obj.getClass().getDeclaredFields();
		if (fields != null) {
			boolean defaultBoost = false,defaultSearch = false;
			if(fieldBoosts.size() == 0)
				defaultBoost = true;
			if(fieldForSearch.size() == 0)
				defaultSearch = true;
			try {
				for (Field field : fields) {
					field.setAccessible(true);
					fieldnameToValue.put(field.getName(), field.get(obj));
					if(defaultBoost)
						fieldBoosts.put(field.getName(), 1.0f);
					if(defaultSearch && field.get(obj) instanceof String){
						fieldForSearch.put(field.getName(), true);
					}
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void Write(Object obj,String fieldname,Object value){
		Field[] fields = obj.getClass().getDeclaredFields();
		if (fields != null) {
			try{
				for (Field field : fields){
					if(field.getName().compareTo(fieldname) == 0){
						field.setAccessible(true);
						field.set(obj, value);
						break;
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	public static Class<?> GetFieldType(Object obj,String fieldname){
		Field[] fields = obj.getClass().getDeclaredFields();
		if (fields != null) {
			try{
				for (Field field : fields){
					if(field.getName().compareTo(fieldname) == 0){
						return field.getType();
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return null;
	}
	public static void clearBoostMap(){
		fieldBoosts.clear();
	}
	
	public static void setBoost(String fieldname,float boost){
		fieldBoosts.put(fieldname, boost);
	}
	
	public static float getBoost(String fieldname){
		return fieldBoosts.get(fieldname);
	}
	
	public static void setNeedSearch(String fieldname,boolean value){
		fieldForSearch.put(fieldname, value);
	}
	
	public static boolean NeedSearch(String fieldname){
		return fieldForSearch.get(fieldname) == null ? false : fieldForSearch.get(fieldname);
	}
	
	public Object getFieldValue(String fieldname){
		return fieldnameToValue.get(fieldname);
	}
	
	public Set<String> getFields(){
		return fieldnameToValue.keySet();
	}

	public HashMap<String, Object> getFieldnameToValue() {
		return fieldnameToValue;
	}
	
	public static void main(String[] args) {
	}
}
